#include "cl_AddItem.h"
#include "ui_cl_AddItem.h"

CL_AddItem::CL_AddItem(QWidget *parent,
                       const QStringList &entries) :
    QDialog(parent),
    ui(new Ui::CL_AddItem)
{
    ui->setupUi(this);

    _id=-1;
    ui->entries->addItems(entries);
    ui->entries->addItem(MANUAL_INPUT);
    ui->entries->setCurrentIndex(-1);
}

CL_AddItem::~CL_AddItem()
{
    delete ui;
}

void CL_AddItem::setEntry(const QString &entry, int version)
{
    ui->entries->setCurrentText(entry);
    if(version < 1002)
        version=1002;
    ui->version->setText(QString::number(version));
}

void CL_AddItem::setItem(int id, const QString &entry, int version, const QString &detail)
{
    _id=id;
    _entry=entry;
    _version=version;
    _detail=detail;

    ui->btn_submit->setText("保存");
    setEntry(entry);
    ui->version->setText(QString::number(version));
    ui->detail->setPlainText(detail);
}

void CL_AddItem::on_entries_currentTextChanged(const QString &entry)
{
    if(entry == MANUAL_INPUT)
    {
        ui->entry->setEnabled(true);
        ui->entry->clear();
    }
    else {
        ui->entry->setText(entry);
        ui->entry->setEnabled(false);
    }
}

void CL_AddItem::on_btn_submit_clicked()
{
    QString versionStr=ui->version->text().trimmed();
    int version=versionStr.toInt();
    if(version == 0)
    {
        MESSAGE_INPUT_ERROR
    }

    QString entry=ui->entry->text().trimmed();
    QString detail=ui->detail->toPlainText();
    if(entry.isEmpty() || detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    QJsonObject obj;
    if(_id > 0)
    {
        obj.insert("id",_id);
        if(entry != _entry)
            obj.insert("entry",entry);

        if(version != _version)
            obj.insert("version",version);

        if(detail != _detail)
            obj.insert("detail",detail);

        if(obj.size() > 1)
            emit updateItem(obj);
    }
    else
    {
        obj.insert("entry",entry);
        obj.insert("version",version);
        obj.insert("detail",detail);
        emit addItem(obj);
    }
    accept();
}
